﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class CardGameManager : MonoBehaviour
{
    /// <summary>
    /// 赢得游戏需要卡牌对数
    /// </summary>
    private const int winCardCouples = 8;
    /// <summary>
    /// 当前匹配成功卡牌对数
    /// </summary>
    private int curCardCouples = 0;
    /// <summary>
    /// 可否翻牌
    /// </summary>
    private bool Clickable = true;

    /// <summary>
    /// 已翻牌次数
    /// </summary>
    public static int Steps = 0;

    public Sprite BackSprite;
    public Sprite SuccSprite;

    /// <summary>
    /// 卡牌正面图案
    /// </summary>
    public Sprite[] FrontSprites;

    private List<GameObject> CardObjs;

    private List<GameObject> CurCardObjs;

    /// <summary>
    /// 当前翻开的牌
    /// </summary>
    private List<Card> FaceCards;

    public GameObject CardPre;

    public Image VictoryImg;

    public GameObject RetryBtn;

    /// <summary>
    /// 存放Panel
    /// </summary>
    public Transform CardsView;

    Coroutine JudgeCoroutine;

    private void Start()
    {
        //窗口化
        Screen.fullScreen = false;
        RetryBtn.GetComponent<Button>().onClick.AddListener(() => RetryBtnOnClick());
        GameInitialize();
    }

    private void GameInitialize()
    {
        Steps = 0;
        curCardCouples = 0;
        //RetryBtn.SetActive(false);
        VictoryImg.enabled = false;
        CurCardObjs = new List<GameObject>();
        CardObjs = new List<GameObject>();
        FaceCards = new List<Card>();
        for (int i = 0; i < FrontSprites.Length; i++)
        {
            Sprite frontSprite = FrontSprites[i];
            //一次添加两对卡牌
            for (int j = 0; j < 4; j++)
            {
                //生成对象
                GameObject obj = Instantiate(CardPre);
                Card card = obj.GetComponent<Card>();
                card.InitCard(i, frontSprite, BackSprite, SuccSprite);
                card.cardBtn.onClick.AddListener(() => CardOnClick(card));                

                CardObjs.Add(obj);
                CurCardObjs.Add(obj);
            }
        }

        //根据列表将卡牌乱序插入
        while (CardObjs.Count > 0)
        {
            int ran = Random.Range(0, CardObjs.Count);
            GameObject obj = CardObjs[ran];
            //obj.transform.parent = CardsView;
            obj.transform.SetParent(CardsView);

            //处理后从列表移除
            CardObjs.RemoveAt(ran);
        }
        Clickable = true;
    }

    private void CardOnClick(Card card)
    {
        if (Clickable)
        {
            //翻牌
            Steps++;
            card.SetCard();
            FaceCards.Add(card);
            //Debug.Log(FaceCards.Count);
            if (FaceCards.Count >= 2)
            {
                Clickable = false;
                JudgeCoroutine = StartCoroutine(JudgeCards());
            }
        }
    }

    /// <summary>
    /// 匹配卡牌
    /// </summary>
    /// <returns></returns>
    private IEnumerator JudgeCards()
    {
        Card card1 = FaceCards[0];
        Card card2 = FaceCards[1];
        if (card1.ID == card2.ID)
        {
            //匹配成功
            //Debug.Log("哇！");
            yield return new WaitForSeconds(0.8f);
            card1.SetSuccess();
            card2.SetSuccess();
            curCardCouples += 1;
            if (curCardCouples == winCardCouples)
            {
                Win();
            }
        }
        else
        {
            //失败
            //Debug.Log("？");
            yield return new WaitForSeconds(1);
            card1.SetRecover();
            card2.SetRecover();
        }

        FaceCards.Clear();
        //Debug.Log("fuck");
        Clickable = true;
    }

    /// <summary>
    /// 过关
    /// </summary>
    private void Win()
    {
        VictoryImg.enabled = true;
        //RetryBtn.SetActive(true);
        if (CurCardObjs.Count > 0)
        {
            foreach (GameObject cardObj in CurCardObjs)
            {
                GameObject.Destroy(cardObj);
            }
        }      
    }

    private void RetryBtnOnClick()
    {
        if (CurCardObjs.Count > 0)
        {
            StopCoroutine(JudgeCoroutine);
            foreach (GameObject cardObj in CurCardObjs)
            {
                //cardObj.GetComponent<Card>().SetRecover();
                GameObject.Destroy(cardObj);
            }
        }
        GameInitialize();
        //RetryBtn.SetActive(false);
    }
}
